#!/usr/bin/env python3
"""
简单的MCP服务器实现 - 不抢占终端控制
"""
import json
import sys
import os
import signal
import threading
import time
from typing import Dict, List, Any, Optional

# 确保不干扰终端控制
os.environ['PYTHONUNBUFFERED'] = '1'

class SimpleMcpServer:
    """简单的MCP服务器实现，专注于不干扰终端控制"""
    
    def __init__(self):
        self.running = True
        self.request_id = 0
        # 注册信号处理
        signal.signal(signal.SIGINT, self.handle_signal)
        signal.signal(signal.SIGTERM, self.handle_signal)
    
    def handle_signal(self, sig, frame):
        """处理信号，确保优雅退出"""
        sys.stderr.write("\n[MCP] 正在安全关闭服务器...\n")
        self.running = False
        sys.exit(0)
    
    def send_response(self, id: int, result: Dict[str, Any], error: Optional[Dict[str, Any]] = None):
        """发送JSON-RPC响应"""
        response = {
            "jsonrpc": "2.0",
            "id": id
        }
        
        if error:
            response["error"] = error
        else:
            response["result"] = result
            
        # 使用stderr输出日志，避免干扰stdout
        sys.stderr.write(f"[MCP] 发送响应: {json.dumps(response)[:100]}...\n")
        
        # 使用stdout发送实际响应
        sys.stdout.write(json.dumps(response) + "\n")
        sys.stdout.flush()
    
    def handle_request(self, request: Dict[str, Any]):
        """处理MCP请求"""
        method = request.get("method", "")
        params = request.get("params", {})
        req_id = request.get("id", 0)
        
        sys.stderr.write(f"[MCP] 收到请求: {method}\n")
        
        if method == "list_tools":
            self.handle_list_tools(req_id)
        elif method == "list_resources":
            self.handle_list_resources(req_id)
        elif method == "call_tool":
            self.handle_call_tool(req_id, params)
        elif method == "read_resource":
            self.handle_read_resource(req_id, params)
        else:
            self.send_response(req_id, None, {
                "code": -32601,
                "message": f"方法不存在: {method}"
            })
    
    def handle_list_tools(self, req_id: int):
        """处理列出工具请求"""
        tools = [
            {
                "name": "echo",
                "description": "简单的回显工具，不会干扰终端",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "message": {
                            "type": "string",
                            "description": "要回显的消息"
                        }
                    },
                    "required": ["message"]
                }
            },
            {
                "name": "get_system_info",
                "description": "获取基本系统信息，不会干扰终端",
                "inputSchema": {
                    "type": "object",
                    "properties": {}
                }
            }
        ]
        
        self.send_response(req_id, {"tools": tools})
    
    def handle_list_resources(self, req_id: int):
        """处理列出资源请求"""
        resources = [
            {
                "uri": "info://system/basic",
                "name": "基本系统信息",
                "mimeType": "application/json",
                "description": "提供基本系统信息的只读资源"
            }
        ]
        
        self.send_response(req_id, {"resources": resources})
    
    def handle_call_tool(self, req_id: int, params: Dict[str, Any]):
        """处理调用工具请求"""
        tool_name = params.get("name", "")
        arguments = params.get("arguments", {})
        
        if tool_name == "echo":
            message = arguments.get("message", "")
            self.send_response(req_id, {
                "content": [
                    {
                        "type": "text",
                        "text": message
                    }
                ]
            })
        elif tool_name == "get_system_info":
            import platform
            
            system_info = {
                "system": platform.system(),
                "release": platform.release(),
                "version": platform.version(),
                "python_version": platform.python_version(),
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            
            self.send_response(req_id, {
                "content": [
                    {
                        "type": "text",
                        "text": json.dumps(system_info, indent=2)
                    }
                ]
            })
        else:
            self.send_response(req_id, None, {
                "code": -32601,
                "message": f"工具不存在: {tool_name}"
            })
    
    def handle_read_resource(self, req_id: int, params: Dict[str, Any]):
        """处理读取资源请求"""
        uri = params.get("uri", "")
        
        if uri == "info://system/basic":
            import platform
            
            system_info = {
                "system": platform.system(),
                "release": platform.release(),
                "version": platform.version(),
                "python_version": platform.python_version(),
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
            }
            
            self.send_response(req_id, {
                "contents": [
                    {
                        "uri": uri,
                        "mimeType": "application/json",
                        "text": json.dumps(system_info, indent=2)
                    }
                ]
            })
        else:
            self.send_response(req_id, None, {
                "code": -32601,
                "message": f"资源不存在: {uri}"
            })
    
    def run(self):
        """运行MCP服务器"""
        sys.stderr.write("[MCP] 服务器启动，等待请求...\n")
        
        # 使用单独的线程处理输入，避免阻塞主线程
        def input_thread():
            while self.running:
                try:
                    line = sys.stdin.readline()
                    if not line:
                        break
                        
                    try:
                        request = json.loads(line)
                        self.handle_request(request)
                    except json.JSONDecodeError:
                        sys.stderr.write("[MCP] 无效的JSON请求\n")
                except Exception as e:
                    sys.stderr.write(f"[MCP] 错误: {str(e)}\n")
        
        thread = threading.Thread(target=input_thread)
        thread.daemon = True
        thread.start()
        
        # 主线程保持活跃，但不干扰终端
        try:
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            sys.stderr.write("\n[MCP] 收到中断信号，正在关闭...\n")
            self.running = False

if __name__ == "__main__":
    server = SimpleMcpServer()
    server.run()